package org.rmc.demo.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
	
	protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e','f' };

	private static final String hexDigits2[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	protected static MessageDigest messagedigest = null;

	
	static {
		try {
//			messagedigest = MessageDigest.getInstance("MD5");
			messagedigest = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			System.err.println("MD5FileUtil messagedigest初始化失败");
			e.printStackTrace();
		}
	}

	public static String MD5Encode(String origin){
		String resultString = null;
		try{
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(origin
					.getBytes()));
		} catch (Exception ex){
			ex.printStackTrace();
		}
		return resultString;
	}

	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits2[d1] + hexDigits2[d2];
	}
 
	/**
	 * 对文件进行MD5加密
	 * 
	 * @author tangwt
	 */
	public static String getFileMD5String(File file) throws IOException {
		@SuppressWarnings("resource")
		FileInputStream in = new FileInputStream(file);
		FileChannel ch = in.getChannel();
		MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		messagedigest.update(byteBuffer);
		return bufferToHex(messagedigest.digest());
	}

    /**
     * 对文件流进行MD5加密
     *
     * @author tangwt
     */
    public static String getFileInputStreamMD5String(FileInputStream fileInputStream) throws IOException {
        @SuppressWarnings("resource")
        FileChannel ch = fileInputStream.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size());
        messagedigest.update(byteBuffer);
        return bufferToHex(messagedigest.digest());
    }

	/**
	 * 对字符串进行MD5加密
	 * 
	 * @author tangwt
	 */
	public static String getMD5String(String s) {
		return getMD5String(s.getBytes());
	}
 
	/**
	 * 对byte类型的数组进行MD5加密
	 * 
	 * @author tangwt
	 */
	public static String getMD5String(byte[] bytes) {
		messagedigest.update(bytes);
		return bufferToHex(messagedigest.digest());
	}
 
	private static String bufferToHex(byte bytes[]) {
		return bufferToHex(bytes, 0, bytes.length);
	}
 
	private static String bufferToHex(byte bytes[], int m, int n) {
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;
		for (int l = m; l < k; l++) {
			char c0 = hexDigits[(bytes[l] & 0xf0) >> 4];
			char c1 = hexDigits[bytes[l] & 0xf];
			stringbuffer.append(c0);
			stringbuffer.append(c1);
		}
		return stringbuffer.toString();
	}

	public static String encryptMD5_2(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		//md.update(str.getBytes("UTF8"));
		byte[] bytes = md.digest(str.getBytes("UTF-8"));
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 255);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}


//	public static void main(String[] args) {
//		String appid = UUID.randomUUID().toString().replaceAll("-", "").substring(0,8);
//		System.out.println(appid);
//		String appkey = MD5Encode("yunsignback" + appid);
//		System.out.println(appkey);
//	}

}
